<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { appState } from '../../../common/manager/appManager'

const props = defineProps({
 icon: {
   type: String
 }
})

const iconHtml = ref()

const loadIcon = async (val:any) => {
   if (!props.icon) {
     iconHtml.value = ''
     return
   }
  iconHtml.value = await loadLocalIcon(val)
}


/**
 * 本地文本文件加载
 * @param name
 * @param asyncFlag
 */
function loadLocalIcon(name:string, asyncFlag = true) {
  return new Promise((resolve, reject) => {
        const url = appState.config.iconPath + name + '.svg'// 直接请求利用浏览器缓存
        const xhr = new XMLHttpRequest()
        xhr.open('GET', url, asyncFlag)
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && xhr.status === 200) {
            const svgString = xhr.responseText
            if (svgString && (svgString.indexOf('<svg') === 0 || svgString.indexOf('<?xml') === 0)) {
              resolve(xhr.responseText)
            } else reject(svgString)
          }
        }
        xhr.send()
      })
}

 watch(() => props.icon, (val:any) => {
   loadIcon(val)
 })

 onMounted(() => {
   loadIcon(props.icon)
 })

</script>

<template>
  <div class="icon-svg-nor" v-html="iconHtml" />
</template>

<style scoped lang="scss">
  .icon-svg-nor{
    @include hor-group(center);
    flex:none;
    width:var(--w-icon-size) ;
    height:var(--w-icon-size) ;
    fill:var(--w-icon-color);
  }
</style>
